package ru.yermak.bookkeeping.account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.yermak.bookkeeping.common.BookkeeperState;
import ru.yermak.bookkeeping.common.UserDao;
import ru.yermak.bookkeeping.common.Command;
import ru.yermak.bookkeeping.model.Account;
import ru.yermak.bookkeeping.model.Group;
import ru.yermak.bookkeeping.model.Currency;
import ru.yermak.bookkeeping.ui.ModalForm;
import ru.yermak.bookkeeping.ui.Selector;
import ru.yermak.bookkeeping.currency.CurrencyDao;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.List;

/**
 * User: harrier
 * Date: Aug 10, 2008
 */

@Scope("action")
@org.springframework.stereotype.Component
public class AccountCreateCommand implements Command {
    private final Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private ModalForm modalForm;
    @Autowired
    private BookkeeperState bookkeeperState;
    @Autowired
    private UserDao userDao;
    @Autowired
    @AccountQulifier
    private Selector selector;
    @Autowired
    private CurrencyDao currencyDao;
    @Autowired
    @AccountQulifier("createForm")
    private JComponent accountCreateForm;
    @Autowired
    @AccountQulifier("accountName")
    private JTextField accountNameField;
    @Autowired
    @AccountQulifier("accountDesc")
    private JTextArea accountDescField;
    @Autowired
    @AccountQulifier("createFormCurrencies")
    private JComponent accountCurrenciesField;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void execute(ActionEvent e) {
        List<Currency> currencies = currencyDao.findCurrencyByUserId(bookkeeperState.getUserId());
        for (Currency currency : currencies) {
            accountCurrenciesField.add(new JCheckBox(currency.getCode()));
        }
        boolean result = modalForm.show(accountCreateForm);
        if (result) {
            log.debug("accountNameField.getText() = " + accountNameField.getText());
            Account account = new Account();
            account.setName(accountNameField.getText());
            account.setDesc(accountDescField.getText());
            Group group = userDao.getGroupById(bookkeeperState.getGroupId());
            account.setGroup(group);
            Integer accountId = accountDao.insertAccount(account);
            selector.rowInserted(accountId);
        }
    }
}
